package utils;

import entity.rtsp.RTSPRequestEntity;
import entity.rtsp.RTSPResponseEntity;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;

public class RTSPUtils {
    public static void requestPacketSend(RTSPRequestEntity rtspRequestEntity, OutputStream out) throws IOException {
        StringBuilder sb = new StringBuilder();

        sb.append(rtspRequestEntity.getMethod()
                + " " + rtspRequestEntity.getTargetUri()
                + " " + rtspRequestEntity.getVersion());
        sb.append("\r\n");
        for(Map.Entry<String, String> entry : rtspRequestEntity.getHeaders().entrySet()){
            sb.append(entry.getKey());
            sb.append(": ");
            sb.append(entry.getValue());
            sb.append("\r\n");
        }
        sb.append("\r\n");
        if(rtspRequestEntity.getBody() != null){
            sb.append(new String(rtspRequestEntity.getBody(), 0, rtspRequestEntity.getBody().length, StandardCharsets.UTF_8));
        }

        out.write(sb.toString().getBytes(StandardCharsets.UTF_8));
    }

    public static void responsePacketSend(RTSPResponseEntity rtspResponseEntity, OutputStream out) throws IOException {
        StringBuilder sb = new StringBuilder();

        sb.append(rtspResponseEntity.getVersion() + " " + rtspResponseEntity.getStatusCode() + " " + rtspResponseEntity.getWord());
        sb.append("\r\n");
        for(Map.Entry<String, String> entry : rtspResponseEntity.getHeaders().entrySet()){
            sb.append(entry.getKey());
            sb.append(": ");
            sb.append(entry.getValue());
            sb.append("\r\n");
        }
        sb.append("\r\n");
        if(rtspResponseEntity.getBody() != null){
            sb.append(rtspResponseEntity.getBody());
        }

        out.write(sb.toString().getBytes(StandardCharsets.UTF_8));
    }

    public static void requestDecorator(RTSPRequestEntity rtspRequestEntity){
        rtspRequestEntity.setTargetUri(
                rtspRequestEntity.getTargetUri().replace(
                        "rtsp://127.0.0.1:" + Consts.getProp("rtsp.listen")
                        ,"rtsp://" + Consts.getProp("rtsp.destIp") + ":" + Consts.getProp("rtsp.destPort")));
    }

    public static String getClientPort(String transport){
        String[] parts = transport.split(";");
        Optional<String> result = Arrays.stream(parts).filter((x) -> x.contains("client_port")).findFirst();
        return result.map(s -> s.substring(s.indexOf("=") + 1)).orElse("");
    }

    public static String getServerPort(String transport){
            String[] parts = transport.split(";");
            Optional<String> result = Arrays.stream(parts).filter((x) -> x.contains("server_port")).findFirst();
            return result.map(s -> s.substring(s.indexOf("=") + 1)).orElse("");
    }
}
